package com.cysyz.mylib.pdf.support;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;

/**
 * 以多个pdf文件的形式来生成结果
 * @author cy
 *
 */
public class PdfGeneraterWithTemplateMutilPdf implements WithTemplatePdfgenerter{

	@Override
	public void generatePdf(OutputFileNameGenerater outputFileNameGenerater,
			ByteArrayOutputStream[] afterReplacedPdfBytes,
			List<List<FieldConfig>> fieldConfigs) throws FileNotFoundException {
		Document document = null;
		PdfCopy copy = null;
		int i = 0;
		for (ByteArrayOutputStream afterRplacedPdfByte : afterReplacedPdfBytes) {
			document = new Document();
			try {
				copy = new PdfCopy(document, new BufferedOutputStream(
						new FileOutputStream(outputFileNameGenerater
								.generate(fieldConfigs.get(i++)))));
				document.open();
				PdfReader afterReplacedPdfReader = new PdfReader(
						afterRplacedPdfByte.toByteArray());
				int numberOfPages = afterReplacedPdfReader.getNumberOfPages();
				for (int ii = 1; ii <= numberOfPages; ii++) {
					PdfImportedPage importedPage = copy.getImportedPage(
							afterReplacedPdfReader, ii);
					copy.addPage(importedPage);
				}
			} catch (FileNotFoundException ex) {
				throw ex;
			} catch (DocumentException | IOException ex) {
				throw new RuntimeException(ex);
			} finally {
				if (copy != null) {
					copy.close();
				}
				if (document != null) {
					document.close();
				}
			}
		}
		
	}

}
